from flask import request
from flask_restx import Resource, Namespace, fields
from app.utils.auth import token_required
from app.utils.validators import validate_required_fields, validate_username
from app.services.admin_service import AdminService
from . import admin_bp

# 创建管理员命名空间
admins_ns = Namespace('admins', description='管理员管理相关接口')

# 定义请求模型
admin_create_request = admins_ns.model('AdminCreateRequest', {
    'admin_name': fields.String(required=True, description='管理员姓名'),
    'username': fields.String(required=True, description='用户名'),
    'password': fields.String(required=True, description='密码'),
    'role_id': fields.Integer(required=True, description='角色ID'),
    'department_id': fields.Integer(description='部门ID'),
    'phone': fields.String(description='电话'),
    'email': fields.String(description='邮箱'),
    'status': fields.Boolean(description='状态')
})

admin_update_request = admins_ns.model('AdminUpdateRequest', {
    'admin_name': fields.String(description='管理员姓名'),
    'username': fields.String(description='用户名'),
    'role_id': fields.Integer(description='角色ID'),
    'department_id': fields.Integer(description='部门ID'),
    'phone': fields.String(description='电话'),
    'email': fields.String(description='邮箱'),
    'status': fields.Boolean(description='状态')
})

# Flask-RESTX兼容的响应函数
def success_response(data=None, message='操作成功', code=200):
    """成功响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

def error_response(message='操作失败', code=400, data=None):
    """错误响应格式 - Flask-RESTX兼容版本"""
    response = {
        'code': code,
        'message': message,
        'data': data
    }
    return response, code

def paginate_response(query, page, per_page, total=None):
    """分页响应格式 - Flask-RESTX兼容版本"""
    if total is None:
        total = query.count()
    
    items = query.offset((page - 1) * per_page).limit(per_page).all()
    
    data = {
        'list': [item.to_dict() if hasattr(item, 'to_dict') else item for item in items],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': total,
            'pages': (total + per_page - 1) // per_page
        }
    }
    
    return success_response(data)

@admins_ns.route('')
class AdminListAPI(Resource):
    """管理员列表"""
    
    @token_required
    def get(self, current_admin):
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int) or request.args.get('limit', 10, type=int)
        
        # 支持多种查询参数名称
        keyword = request.args.get('keyword', '') or request.args.get('name', '') or request.args.get('username', '')
        status = request.args.get('status', type=int) or request.args.get('is_active', type=int)
        
        if status is not None:
            status = bool(status)
        
        query, page, per_page = AdminService.get_list(page, per_page, keyword, status)
        return paginate_response(query, page, per_page)
    
    @admins_ns.expect(admin_create_request)
    @token_required
    def post(self, current_admin):
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['admin_name', 'username', 'password', 'role_id'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        
        # 验证用户名格式
        if not validate_username(data.get('username')):
            return error_response('用户名格式不正确', 400)
        
        # 检查用户名是否已存在
        existing_admin = AdminService.get_by_username(data.get('username'))
        if existing_admin:
            return error_response('用户名已存在', 400)
        
        try:
            admin = AdminService.create(data)
            return success_response(admin.to_dict(), '创建成功')
        except Exception as e:
            return error_response(f'创建失败：{str(e)}', 500)


@admins_ns.route('/<int:admin_id>')
class AdminDetailAPI(Resource):
    """管理员详情"""
    
    @token_required
    def get(self, current_admin, admin_id):
        admin = AdminService.get_by_id(admin_id)
        if not admin:
            return error_response('管理员不存在', 404)
        
        return success_response(admin.to_dict())
    
    @admins_ns.expect(admin_update_request)
    @token_required
    def put(self, current_admin, admin_id):
        admin = AdminService.get_by_id(admin_id)
        if not admin:
            return error_response('管理员不存在', 404)
        
        data = request.get_json()
        
        # 如果修改用户名，检查是否重复
        if 'username' in data and data['username'] != admin.username:
            existing_admin = AdminService.get_by_username(data.get('username'))
            if existing_admin:
                return error_response('用户名已存在', 400)
        
        try:
            updated_admin = AdminService.update(admin_id, data)
            return success_response(updated_admin.to_dict(), '更新成功')
        except Exception as e:
            return error_response(f'更新失败：{str(e)}', 500)
    
    @token_required
    def delete(self, current_admin, admin_id):
        # 不能删除自己
        if admin_id == current_admin.id:
            return error_response('不能删除自己', 400)
        
        success = AdminService.delete(admin_id)
        if not success:
            return error_response('删除失败，管理员不存在', 404)
        
        return success_response(message='删除成功')


@admins_ns.route('/options')
class AdminOptionsAPI(Resource):
    """管理员选项数据"""
    
    @token_required
    def get(self, current_admin):
        option_type = request.args.get('type')
        
        if option_type == 'roles':
            data = AdminService.get_role_options()
        elif option_type == 'departments':
            data = AdminService.get_department_options()
        else:
            return error_response('无效的选项类型', 400)
        
        return success_response(data)


# 将命名空间注册到统一的API实例
from . import api
api.add_namespace(admins_ns, path='/admins') 